package com.yxh.activity;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yxh.R;
import com.yxh.adapter.ClassAdapter;
import com.yxh.dto.LessonDto;
import com.yxh.dto.UserDto;
import com.yxh.fragment.HomeFragment;
import com.yxh.service.Task;
import com.yxh.util.AppUtils;
import com.yxh.util.LogUtil;
import com.yxh.view.CommonDialog;
import com.yxh.view.LoadingLayout;
import com.yxh.view.pulltorefresh.PullToRefreshBase;
import com.yxh.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.yxh.view.pulltorefresh.PullToRefreshScrollView;
import com.yxh.view.swipemenulistview.SwipeMenu;
import com.yxh.view.swipemenulistview.SwipeMenuCreator;
import com.yxh.view.swipemenulistview.SwipeMenuItem;
import com.yxh.view.swipemenulistview.SwipeMenuListView;

/**
 * 我的课程 Activity
 * 
 */

public class AboutMeClassActivity extends BaseActivity {

	private LoadingLayout loadingLayout;
	private SwipeMenuListView listView;
	private List<LessonDto> cList;
	private ClassAdapter adapter;
	private int[] noScrowArray;
	private PullToRefreshScrollView mPullRefreshScrollView;
	@SuppressWarnings("unused")
	private String resouce;// 0:aboutMeFragment 1:ClassSelectActivity

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_about_me_class);

		initViews();

		initData();

		initRegisterReceiver();

		overridePendingTransition(R.anim.enter_righttoleft, R.anim.noanim);
	}

	private void initViews() {

		resouce = this.getIntent().getStringExtra("resource");

		/** loading view **/
		loadingLayout = (LoadingLayout) findViewById(R.id.loading_layout);
		loadingLayout.showLoading();
		loadingLayout.setOnRetryClickListener((new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				initData();
			}
		}));

		/*** top view ***/
		((TextView) findViewById(R.id.head_layout_tv)).setText("我的课程");

		/*** inti Listview ***/
		listView = (SwipeMenuListView) findViewById(R.id.listView);
		cList = new ArrayList<LessonDto>();
		adapter = new ClassAdapter(mContext, cList);

		noScrowArray = new int[] { -1, -1, -1 };
		listView.setNoScorwArray(noScrowArray);
		listView.setAdapter(adapter);
		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);
				deleteItem
						.setBackground(R.drawable.main_home_bottom_list_right_bg);
				deleteItem.setWidth(AppUtils.dp2px(mContext, 75));
				deleteItem.setIcon(R.drawable.class_listview_delete);
				menu.addMenuItem(deleteItem);
			}
		};

		listView.setMenuCreator(creator);
		listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu,
					int index) {
				switch (index) {

				case 0:
					goCancleLesson(cList.get(position).lessonId);
					break;

				default:
					break;
				}
				return false;
			}
		});

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {

				LessonDto lDto = cList.get(pos);
				if ("0".equals(lDto.state)) {// 0:当前
					Intent it = new Intent(mContext,
							ClassTimeSettingActivity.class);
					it.putExtra("resource", "3");
					it.putExtra("dto", lDto);
					startActivity(it);
				} else if ("1".equals(lDto.state)) {// 1:已完成
					showReAddClassDialog(lDto.lessonId);
				} else if ("2".equals(lDto.state)) {// 2: 已取消
					showReAddClassDialog(lDto.lessonId);
				}
			}

		});

		mPullRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
		mPullRefreshScrollView
				.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ScrollView> refreshView) {
						getMyClassData(0);
					}
				});

	}

	private void initData() {

//		long t1 = System.currentTimeMillis();

		loadingLayout.showLoading();
		getMyClassData(0);

//		long t2 = System.currentTimeMillis();

//		LogUtil.e("t2-t1 -->" + (t2 - t1));
	}

	private void getMyClassData(int isShowDialog) {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/mine");
		getData(map, Task.GET_MY_LESSON, isShowDialog);
	}

	private void goCancleLesson(String lesson_id) {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/cancel");
		map.put("lesson_id", lesson_id);
		getData(map, Task.CANCEL_LESSON, 1);

	}

	private void showReAddClassDialog(final String lessonId) {

		AppUtils.showNoTitleDialog(this, "您是否要重新添加该课程?", new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
				goAddClass(lessonId);
			}
		}, new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
			}

		});
	}

	private void goAddClass(String lessonId) {
		if (TextUtils.isEmpty(lessonId)) {
			LogUtil.e("课程添加参数异常");
			return;
		}
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/add_lesson");
		map.put("lesson_ids", lessonId);
		getData(map, Task.ADD_LESSON_CLASS_ACTIVITY, 1);

	}

	/**
	 * 刷新当前数据
	 */
	private void refrushData(List<LessonDto> li) {
		if (mPullRefreshScrollView != null)
			mPullRefreshScrollView.onRefreshComplete();
		cList.clear();
		cList.addAll(li);
		noScrowArray[0] = -1;
		noScrowArray[1] = -1;
		noScrowArray[2] = -1;

		for (int i = 0; i < cList.size(); i++) {
			if (cList.get(i).state.equals("0") && noScrowArray[0] == -1) {
				noScrowArray[0] = i;
				cList.add(noScrowArray[0],
						new LessonDto("-1", String.valueOf(0), "0"));
			} else if (cList.get(i).state.equals("1") && noScrowArray[1] == -1) {
				noScrowArray[1] = i;
				cList.add(noScrowArray[1],
						new LessonDto("-1", String.valueOf(1), "0"));
			} else if (cList.get(i).state.equals("2") && noScrowArray[2] == -1) {
				noScrowArray[2] = i;
				cList.add(noScrowArray[2],
						new LessonDto("-1", String.valueOf(2), "0"));
			} else {
				cList.get(i).isTitle = "1";
			}
		}

		listView.setNoScorwArray(noScrowArray);
		adapter.notifyDataSetChanged();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void refresh(Object... param) {
		try {
			int operType = (Integer) param[0];
			Object obj = param[1];
			switch (operType) {
			case Task.GET_MY_LESSON:
				closeDialog();
				if (obj != null) {
					List<LessonDto> li = (ArrayList<LessonDto>) obj;
					if ("1".equals(li.get(0).result)) {
						loadingLayout.showContent();
						refrushData(li);
					} else {
						loadingLayout.showEmpty();
						showToast(li.get(0).message);
					}

				} else {
					loadingLayout.showError();
					showToast(getString(R.string.http_no_net_tip));
				}
				break;

			case Task.CANCEL_LESSON:

				if (obj != null) {
					UserDto dto = (UserDto) obj;
					if ("1".equals(dto.result)) {
						getMyClassData(1);
						sendBroadcast(new Intent(
								HomeFragment.REFRUSH_HOME_DEL_CLASS));
					} else {
						closeDialog();
						showToast(dto.message);
					}

				} else {
					closeDialog();
					showToast(getString(R.string.http_no_net_tip));
				}
				break;

			case Task.ADD_LESSON_CLASS_ACTIVITY:
				if (obj != null) {
					List<LessonDto> li = (ArrayList<LessonDto>) obj;
					if ("1".equals(li.get(0).result)) {
						getMyClassData(1);
						sendBroadcast(new Intent(
								HomeFragment.REFRUSH_HOME_ADD_CLASS));
					} else {
						closeDialog();
						showToast(li.get(0).message);
					}
				} else {
					closeDialog();
					showToast(getString(R.string.http_no_net_tip));
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 广播
	 */
	public static final String COM_REFRUSH_CLASS = "refresh.classactivity.for.settingtime";
	private BroadcastReceiver classReceiver;

	private void initRegisterReceiver() {
		classReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent i) {
				String action = i.getAction();
				if (action.equals(COM_REFRUSH_CLASS)) {
					getMyClassData(1);// 刷新Fragment
				}
			}
		};

		IntentFilter i = new IntentFilter();
		i.addAction(COM_REFRUSH_CLASS);
		registerReceiver(classReceiver, i);
	}

	private void unregisterReceiver() {
		unregisterReceiver(classReceiver);
	}

	@Override
	public void onDestroy() {
		unregisterReceiver();
		super.onDestroy();
	}
}
